const models = require("../db/mysqldb/index");
const { Op } = require("sequelize");

class DataSystemRoleModel {
  /**
   * @description 通过 role_id 查找数据，不包含删除数据
   * @param {string} role_id
   * @returns
   */
   static async findBySystemRoleId({ role_id }) {
    return await models.sys_role.findOne({
      where: {
        role_id,
      },
    });
  }
  /**
   * @description 更新数据
   * @param {*} op_user_id
   * @param {*} role_id
   * @param {*} status
   * @returns
   */
  static async updateStatus({ op_user_id, role_id, status }) {
    console.log(op_user_id, role_id, status);
    return await models.sys_role.update(
      {
        status,
        update_time: Date.now(),
        update_by: op_user_id,
      },
      {
        where: { role_id },
      }
    );
  }
  /**
   * @description 通过 role_id 查找数据，不包含删除数据
   * @param {string} role_id
   * @returns
   */
  static async findBySystemRoleId({ role_id }) {
    return await models.sys_role.findOne({
      where: {
        role_id,
      },
    });
  }
  /**
   * @description 通过 role_name 查找数据，不包含删除数据
   * @param {string} role_name
   * @returns
   */
  static async findBySystemRoleName({ role_name }) {
    return await models.sys_role.findOne({
      where: {
        role_name,
        del_flag: "0",
      },
    });
  }
  /**
   * @description 通过 role_key 查找数据，不包含删除数据
   * @param {string} role_key
   * @returns
   */
  static async findBySystemRoleCode({ role_key }) {
    return await models.sys_role.findOne({
      where: {
        role_key,
        del_flag: "0",
      },
    });
  }
  /**
   * @description 通过 role_name id 查找数据，不包含删除数据
   * @param {string} role_name
   * @param {string} role_id
   * @returns
   */
  static async findBySystemRoleNameNeId({ role_name, role_id }) {
    return await models.sys_role.findOne({
      where: {
        role_name,
        del_flag: "0",
        role_id: {
          [Op.ne]: role_id,
        },
      },
    });
  }
  /**
   * @description 通过 role_key id 查找数据，不包含删除数据
   * @param {string} role_key
   * @param {string} role_id
   * @returns
   */
  static async findBySystemRoleKeyNeId({ role_key, role_id }) {
    return await models.sys_role.findOne({
      where: {
        role_key,
        del_flag: "0",
        role_id: {
          [Op.ne]: role_id,
        },
      },
    });
  }
  /**
   * @description create
   * @param {String} role_key
   * @param {String} role_name
   * @param {Number} role_sort
   * @param {String} data_scope
   * @param {String} menu_check_strictly
   * @param {String} dept_check_strictly
   * @param {String} status
   * @param {String} remark
   * @param {String} op_user_id
   * @returns
   */
  static async create({
    role_key,
    role_name,
    role_sort,
    data_scope,
    menu_check_strictly,
    dept_check_strictly,
    status,
    remark,
    op_user_id,
    menu_ids,
  }) {
    let role_id;
    return await models.sequelize.transaction(function (t) {
      return models.sys_role
        .create(
          {
            role_key,
            role_name,
            role_sort,
            data_scope,
            menu_check_strictly,
            dept_check_strictly,
            status,
            remark,
            create_by: op_user_id,
            create_time: Date.now(),
          },
          { transaction: t }
        )
        .then((role) => {
          role_id = role.role_id;
          return models.sys_role_menu.destroy({
            where: { role_id },
            transaction: t,
          });
        })
        .then(() => {
          if (menu_ids.length && role_id) {
            let data = menu_ids.map((item) => {
              return {
                menu_id: item,
                role_id,
              };
            });
            return models.sys_role_menu.bulkCreate(data, { transaction: t });
          }
        })
        .catch((err) => {
          console.log(err.message);
          return t.rollback();
        });
    });
  }
  /**
   * @description create
   * @param {Number} role_id
   * @param {String} data_scope
   * @param {String} dept_check_strictly
   * @param {String} op_user_id
   * @returns
   */
  static async updateDateScope({
    data_scope,
    op_user_id,
    role_id,
    dept_check_strictly,
  }) {
    return await models.sequelize.transaction(function (t) {
      return models.sys_role
        .update(
          {
            dept_check_strictly,
            data_scope,
            create_by: op_user_id,
            create_time: Date.now(),
          },
          {
            where: { role_id },
            transaction: t,
          }
        )
        .then(() => {
          return models.sys_role_menu.destroy({
            where: { role_id },
            transaction: t,
          });
        })
        .then(() => {
          if (menu_ids.length) {
            let data = menu_ids.map((item) => {
              return {
                menu_id: item,
                role_id,
              };
            });
            return models.sys_role_menu.bulkCreate(data, { transaction: t });
          }
        })
        .catch((err) => {
          console.log(err.message);
          return t.rollback();
        });
    });
  }
  /**
   * @description 更新
   * @param {String} role_key
   * @param {String} role_name
   * @param {Number} role_sort
   * @param {String} data_scope
   * @param {String} menu_check_strictly
   * @param {String} dept_check_strictly
   * @param {String} status
   * @param {String} remark
   * @param {String} op_user_id
   * @param {Number} role_id
   * @returns
   */
  static async update({
    role_key,
    role_name,
    role_sort,
    data_scope,
    menu_check_strictly,
    dept_check_strictly,
    status,
    remark,
    op_user_id,
    role_id,
  }) {
    return await models.sys_role.update(
      {
        role_key,
        role_name,
        role_sort,
        data_scope,
        menu_check_strictly,
        dept_check_strictly,
        status,
        remark,
        update_by: op_user_id,
        update_time: Date.now(),
      },
      {
        where: { role_id },
      }
    );
  }
  /**
   * @description 更新 dataScope 数据权限
   * @param {String} data_scope
   * @param {Number} role_id
   * @returns
   */
  static async update({ data_scope, op_user_id, role_id }) {
    return await models.sys_role.update(
      {
        data_scope,
        update_by: op_user_id,
        update_time: Date.now(),
      },
      {
        where: { role_id },
      }
    );
  }
  /**
   * @description 删除
   * @param {*} op_user_id
   * @param {*} role_id
   * @returns
   */
  static async delete({ op_user_id, role_id }) {
    return await models.sys_role.update(
      {
        del_flag: "2",
        update_by: op_user_id,
      },
      {
        where: { role_id },
      }
    );
  }

  /**
   * @description 批量删除
   * @param {Number} op_user_id
   * @param {Array} ids
   * @returns
   */
  static async deleteByIds({ op_user_id, ids }) {
    return await models.sys_role.update(
      {
        del_flag: "2",
        update_by: op_user_id,
      },
      {
        where: {
          role_id: {
            [Op.in]: ids,
          },
        },
      }
    );
  }

  /**
   * @description 获取权限信息
   * @param {String} role_name
   * @param {String} is_frame
   * @returns
   */
  static async list({ limit, size, role_name, role_key, status }) {
    let querySql = "";
    if (role_name) {
      querySql += ` and role_name like '%${role_name}%'`;
    }
    if (role_key) {
      querySql += ` and role_key like '%${role_key}%'`;
    }
    if (status) {
      querySql += ` and status = ${status}`;
    }
    let sql = `
      SELECT
      role_id,role_name,role_key,role_sort,data_scope,
      menu_check_strictly,dept_check_strictly,status,remark,create_time
    FROM
    sys_role WHERE del_flag = '0' ${querySql}
    ORDER BY
      role_sort ASC,
      create_time DESC,
      update_time DESC limit ${(limit - 1) * size}, ${size}`;
    const result = await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
    const count = await models.sequelize.query(
      `SELECT count(1) as count FROM
      sys_role WHERE del_flag = '0' ${querySql};`,
      { replacements: ["active"], type: models.sequelize.QueryTypes.SELECT }
    );
    return {
      result,
      count,
    };
  }
  /**
   * @description 获取权限信息
   * @param {String} role_name
   * @param {String} is_frame
   * @returns
   */
   static async findList({ role_name, role_key, status, data_scope }) {
    let querySql = "";
    if (role_name) {
      querySql += ` and role_name like '%${role_name}%'`;
    }
    if (role_key) {
      querySql += ` and role_key like '%${role_key}%'`;
    }
    if (status) {
      querySql += ` and status = ${status}`;
    }
    let sql = `
      SELECT
      role_id,role_name,role_key,role_sort,data_scope,
      menu_check_strictly,dept_check_strictly,status,remark,create_time
    FROM
    sys_role WHERE del_flag = '0' ${querySql} ${data_scope}
    ORDER BY
      role_sort ASC,
      create_time DESC,
      update_time DESC`;
    const result = await models.sequelize.query(sql, {
      replacements: ["active"],
      type: models.sequelize.QueryTypes.SELECT,
    });
    return {
      result,
    };
  }
}
module.exports = {
  DataSystemRoleModel,
};
